import {getUserInfo, delMsg, getMessageList, unLockFunc} from '../../api/member.js';
import {getUnreadMsg} from '../../api/api.js';

import Util from '../../utils/util.js';

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false, // 是否加载中
    loadend: false, // 是否加载完毕
    loadTitle: '加载更多内容', // 提示语
    lists: [],
    page: 1,
    et_show: true,
    address: "",
    showTipDialog: false,

    navs: [
      {title: "互选成功", icon: "suc", link: "suc"},
      {title: "超级心动", icon: "love", link: "suc?type=love"},
      {title: "我应征的", icon: "send", link: "enlist"},
      {title: "应征我的", icon: "sended", link: "enlistor"},
      // {title: "最近来访", icon: "visit", link: "../member-visit/index"},
    ],

    isOnLoading: true,

    startX: 0,
    startY: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    this.setData({
      userInfo: app.globalData.userInfo || [],
      isIphoneX: app.globalData.isIphoneX
    });

    wx.showLoading({
      title: "正在加载..."
    })
    this.setData({
      isOnLoading: false
    })
    Util.chekWxLogin().then(res => {
      that.setData({userInfo: res.userInfo})
      this.setData({
        loadend: false,
        loading: false,
        page: 1,
        isOnLoading: true,
        lists: []
      });

      this.getLists()

      wx.hideLoading()
    }).catch(errmsg => {
      wx.hideLoading()
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this,
      is_refresh = wx.getStorageSync('is_refresh')

    if (is_refresh) {
      this.setData({
        loadend: false,
        loading: false,
        page: 1,
        lists: []
      });

      this.getLists()
      wx.removeStorageSync('is_refresh')
    }

    if (!Util.isEmpty(this.data.userInfo) && this.data.userInfo.is_subscribe != 1) {
      //关注公众号
      this.setData({
        dialogProfile: false,
        dialogType: "service_subscribe_click"
      })
    } else {
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  getLists() {
    const that = this
    let lists = that.data.lists || []

    if (that.data.loadend || that.data.loading) {
      return;
    }
    that.setData({loading: true, loadTitle: '加载更多内容'});

    let filter = that.data.filter || {}
    filter['page_num'] = that.data.page;
    filter['original'] = 1;

    getMessageList(filter).then(res => {
      const list = res.data.items || []
      const loadend = res.data.last_page <= that.data.page;
      lists = app.SplitArray(list, lists);

      if (that.data.page == 1) {
        that.setData({
          system_message: res.data.system_message || null,
          unlock_type: res.data.unlock_type || null,
          member: res.data.member || null,
          reply_amount: res.data.reply_amount || 0
        })
      }

      that.setData({
        lists: lists,
        loadend: loadend,
        loading: false,
        loadTitle: loadend ? '已全部加载' : '正在加载...',
        // total_unread: res.data.total_unread,
        page: that.data.page + 1,
        et_show: lists.length > 0
      });

      wx.stopPullDownRefresh()
    }).catch(errmsg => {
      wx.stopPullDownRefresh()
      app.Tips({title: errmsg})
    })
  },

  bindUnlock(e) { //显示解锁弹窗
    this.setData({
      memberComboDialog: true
    })
  },

  dialogCancel(e) {
    const that = this,
      dialog_data = e.detail;
    // && dialog_data.field == 'filter'
    if (!Util.isEmpty(dialog_data.field)) {
      this.setData({
        memberComboDialog: true
      })
      return
    }
  },

  confirmMemberComboDialog(e) {
    if (!Util.isEmpty(e.detail.is_vip) && e.detail.is_vip == 1 && !Util.isEmpty(this.data.member)) {
      let member = this.data.member
      member.is_vip = 1;
      this.setData({
        member: member
      })
      return
    }
  },

  //弹窗回调
  dialogConfirm(e) {
    const that = this,
      dialog_data = e.detail;
  },

  del(e) {
    const that = this,
      key = e.currentTarget.dataset.index

    let lists = that.data.lists || []
    wx.showModal({
      title: '消息删除后将不可恢复，确认删除吗？',
      content: '',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: "#EF6243",
      success: (res) => {
        if (res.confirm) {
          delMsg(lists[key].id).then(res => {
            lists.splice(key, 1)
            that.setData({
              lists: lists
            })
          }).catch(errmsg => {
            app.Tips({title: errmsg})
          })
        }
      }
    })
  },

  /**
   * 手指触摸动作开始，记录起始点
   */
  touchstart(e) {
    const pageX = e.changedTouches[0].pageX
    const pageY = e.changedTouches[0].pageY;
    // 遍历moveList，把每一项的isView设置为true
    this.data.lists.forEach((item, index) => {
      if (item.isView) {
        item.isView = false
      }
    })
    this.setData({
      startX: pageX,
      startY: pageY,
      lists: this.data.lists
    })
  },

  /**
   * 滑动事件处理
   */
  touchmove(e) {
    const pageX = e.changedTouches[0].pageX;//结束时X坐标
    const pageY = e.changedTouches[0].pageY;//结束时Y坐标
    const startX = this.data.startX;//开始时X坐标
    const startY = this.data.startY;//开始时Y坐标
    const that = this
    // 获取华东角度
    const angle = this.angle({X: startX, Y: startY}, {X: pageX, Y: pageY})
    // 当前索引
    const index = e.currentTarget.dataset.index
    this.data.lists.forEach((item, i) => {
      // 1.如果滑动角度大于30度，直接返回
      //2.如果开始位置小于结束位置，说明时向右滑动

      if (Math.abs(angle > 30)) {
        return
      }
      if (i == index) {
        if (that.data.startX < pageX) {//右滑
          item.isView = false
        } else {
          //左滑
          item.isView = true
        }
      }
    })

    this.setData({
      lists: this.data.lists
    })
  },

  /**
   * 计算角度的函数
   */
  angle: function (start, end) {
    var _X = start.X - end.X;
    var _Y = start.Y - end.Y;
    //   返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI)
  },

  showServiceDialog(e) {  //服务号弹窗
    this.setData({
      dialogType: ""
    })
    //关注公众号
    this.setData({
      dialogType: "service_subscribe_click"
    })

  },

  showMsgTip(e) {
    const index = e.currentTarget.dataset.index
    const item = index.send_member.cancel
    // if(item == 0){
    //   app.Tips({ title: "对方已注销，无法查看", hideMask: true })
    //   return
    // }
    wx.navigateTo({
      url: "detail?suid=" + index.uid + "&msg_id=" + index.id,
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      loadend: false,
      loading: false,
      page: 1,
      lists: []
    });
    this.getLists()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getLists()
  },

  tabStat(e) {
    let navs = this.data.navs
    if (!Util.isEmpty(e.detail) && e.detail.visit_amount > 0 && navs[3].icon == 'visit') {
      navs[3].amount = e.detail.visit_amount;
      this.setData({
        navs: navs
      })
    }
  },

  onLoadTabbar: function (e) {//底部tabbar返回数据
    this.setData({
      bottom: parseInt(e.detail) + 15
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})